<?php
class OLM_Permissions
{
	static function refreshACLFile()
	{
		$actions = Permissions_Actions::find('action!=?', '')->asArray()->getAll();
		foreach ($actions as $a)
		{
			$mapping = Roles_Actions_Mapping::find('roles_actions_mapping.permissions_actions_id=?', $a['id'])->asArray()->getAll();
			$acl[$a['namespace']]['all_controllers']['allow'] = '"1"';
			if ($a['roles_access_control'] != 'ACL_NULL')
			{
				if ($a['namespace'] == 'default')
				{
					$acl[$a['controller']]['actions'][$a['action']]['allow'] = $a['roles_access_control'];
				}
				else
				{
					$acl[$a['namespace']][$a['controller']]['actions'][$a['action']]['allow'] = $a['roles_access_control'];
				}
			}
			elseif ( ! empty($mapping))
			{
				$roles = array();
				foreach ($mapping as $m)
				{
					$roles_mapping = Roles_Users_Mapping::find('roles_id=?', $m['roles_id'])->asArray()->getAll();
					foreach ($roles_mapping as $r)
					{
						$roles[$r['user_id']] = $r['user_id'];
					}
				}
				$roles = implode(',', $roles);
				if ($a['namespace'] == 'default')
				{
					$acl[$a['controller']]['actions']['all_actions']['allow'] = '"1"';
					$acl[$a['controller']]['actions'][$a['action']]['allow'] = '"' . $roles . '"';
				}
				else
				{
					$acl[$a['namespace']][$a['controller']]['actions']['all_actions']['allow'] = '"1"';
					$acl[$a['namespace']][$a['controller']]['actions'][$a['action']]['allow'] = '"' . $roles . '"';
				}
			}
		}
		$spyc = new Helper_BSS_Spyc();
		$acl_yaml = "# <?php die(); ?>\n\n".$spyc->YAMLDump($acl);
		$acl_filename = Q::ini('app_config/CONFIG_DIR') . DS . 'acl.' . Q::ini('app_config/CONFIG_FILE_EXTNAME');
		$handle = fopen($acl_filename, "w+");
		if (fwrite($handle, $acl_yaml))
		{
			fclose($handle);
			Q::cleanCache(Q::ini('app_config/APPID').'_app_config');
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			fclose($fp);
			return array('ack' => FAILURE, 'message' => '');
		}
	}
}